﻿using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using System.Web.Security;
using EpiInfoCloudMagpiBridge.Models;
using Ewav.Security;

namespace EpiInfoCloudMagpiBridge.Controllers
{
    [Authorize]
    public class MagpiAzureMappingController : Controller
    {

        string _baseAddressMagpiServer_Data = ConfigurationManager.AppSettings["baseAddressMagpiServer_Data"];
        string _baseAddressMagpiServer_SurveyList = ConfigurationManager.AppSettings["baseAddressMagpiServer_SurveyList"];
        //Sachin: MagpiEwavMobileService - is MobileServiceName from db. Will have to replaced in the URL above.  
        //Sachin: "http://" + MobileServiceName + "baseAddress - which is azure-mobile.net/"
        const string _ewavAzureServiceDirective = "tables/";


        readonly Cryptography cy = new Cryptography();


        List<MagpiAzureMapping> _AllMagmpList;

        //    readonly Cryptography cy = new Cryptography();
        MagpiEWAVEntities db;


        public MagpiAzureMappingController()
        {



        }


        // GET: MagpiAzureMapping
        public ActionResult Index()
        {
            // Get list of registered ahd unregistered Magpi datasets    
            MagpiAzureMappingHelper magpiAzureMappingHelper = _getMagpiLists();



            return View(magpiAzureMappingHelper);

        }

        [HttpPost]
        public ActionResult Save()
        {

            // Get complete magpi list     
            List<MagpiAzureMapping> AllMagmpList = new List<MagpiAzureMapping>();


            MagpiAzureMapping magpiAzureMapping = new MagpiAzureMapping
            {
                EWAVUserID = ApplicationModel.CurrentEwavUserId,
                SurveyID = this.Request.Form["ddlSurveys"],
                MobileServiceTableName = this.Request.Form["txtMobileServiceTableName"]
            };

            _AllMagmpList = HelperFunctions.getAllMagpiSurveys();

            var IE_filteredSurveyList = from magpi in _AllMagmpList
                                        where magpi.SurveyID == magpiAzureMapping.SurveyID
                                        select magpi;

            List<MagpiAzureMapping> selectedSurveyList = IE_filteredSurveyList.ToList();

            magpiAzureMapping.SurveyName = selectedSurveyList[0].SurveyName;
            magpiAzureMapping.Owner = selectedSurveyList[0].Owner;


            var context = new MagpiEWAVEntities(cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));
            context.MagpiAzureMappings.Add(magpiAzureMapping);
            context.SaveChanges();


            string yy = this.Request.Form["DropDownCollection.SelectedItemId"];
            string zz = this.Request.Form["txtMobileServiceTableName"];




            // Get list of registered ahd unregistered Magpi datasets    
            MagpiAzureMappingHelper magpiAzureMappingHelper = _getMagpiLists();


            return View("Index", magpiAzureMappingHelper);

            //    return View();

        }


        private MagpiAzureMappingHelper _getMagpiLists()
        {


            MagpiAzureMappingHelper mamh = new MagpiAzureMappingHelper();

            // First get list of surveys already reistered from Azure  
            MagpiEWAVEntities context = new MagpiEWAVEntities(cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));
            mamh.MagpiAzureRegisteredList =
                context.MagpiAzureMappings.Where(
                    x => x.EWAVUserID == ApplicationModel.CurrentEwavUserId).ToList();


            _AllMagmpList = HelperFunctions.getAllMagpiSurveys();



            // Next get list of all surveys from Magpi            
            mamh.MagpiTotalList = _AllMagmpList;

            // Next get list of surveys from Magpi not registered yet with Azure    
            var notRegistered = mamh.MagpiTotalList.Where(
                magpiTotal => !mamh.MagpiAzureRegisteredList.Any(
                AzureRegistered => AzureRegistered.SurveyID == magpiTotal.SurveyID));


            mamh.MagpiNotRegisteredList = notRegistered.ToList();


            return mamh;

        }


        // GET: MagpiAzureMapping/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: MagpiAzureMapping/Create
        public ActionResult Create()
        {


            // Get list of registered ahd unregistered Magpi datasets    
            MagpiAzureMappingHelper magpiAzureMappingHelper = _getMagpiLists();



            //  return View();                          

            return View(magpiAzureMappingHelper);

        }

        // POST: MagpiAzureMapping/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: MagpiAzureMapping/Edit/5
        public ActionResult Edit(int id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            db =
                new MagpiEWAVEntities(
                    cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));


            MagpiAzureMapping magpiAzureMapping = db.MagpiAzureMappings.Find(id);
            if (magpiAzureMapping == null)
            {
                return HttpNotFound();
            }
            return View(magpiAzureMapping);
        }

        // POST: MagpiAzureMapping/Edit/5
        [HttpPost]
        //     public ActionResult Edit(int id, FormCollection collection)
        public ActionResult Edit(MagpiAzureMapping magpiAzureMapping)
        {

            if (ModelState.IsValid)
            {

                db = new MagpiEWAVEntities(
                    cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));

           
                magpiAzureMapping.EWAVUserID = ApplicationModel.CurrentEwavUserId;
                db.Entry(magpiAzureMapping).State = EntityState.Modified;  
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(magpiAzureMapping);


            //try
            //{
            //    // TODO: Add update logic here

            //    return RedirectToAction("Index");
            //}
            //catch
            //{
            //    return View();
            //}
        }




        // GET: MagpiAccountSettings/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            MagpiEWAVEntities db = new MagpiEWAVEntities(cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));
            MagpiAzureMapping magpiAzureMapping = db.MagpiAzureMappings.Find(id);
            if (magpiAzureMapping == null)
            {
                return HttpNotFound();
            }
            return View(magpiAzureMapping);
        }

        // POST: MagpiAccountSettings/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            MagpiEWAVEntities db = new MagpiEWAVEntities(cy.Decrypt(ConfigurationManager.ConnectionStrings["MagpiEWAVEntities"].ToString()));
            MagpiAzureMapping magpiAzureMapping = db.MagpiAzureMappings.Find(id);
            db.MagpiAzureMappings.Remove(magpiAzureMapping);
            db.SaveChanges();
            return RedirectToAction("Index");
        }


    }
}
